#include "CChatSession.h"
#include "CChatServer.h"
#include "CLoginHandler.h"
#include "CLogoutHandler.h"
CChatSession::CChatSession(CChatServer *cs, QTcpSocket *s,QObject *parent) : QObject(parent)
{
    server=cs;
    terminator="\n";
    data.clear();
    socket=s;
    connect(socket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    shunt(new CLoginHandler(cs,parent));
}

void CChatSession::shunt(CHandler *r)
{
    CHandler*cur=r;
    cur->remove(this);
    room=r;
    room->add(this);
}

void CChatSession::collectIncomingData(QByteArray bytes)
{
    data.append(bytes.replace("\n",""));
}

void CChatSession::foundTerminator()
{
    QByteArray line=data;
    data.clear();
    try{
        room->handle(this,line);
    }
    catch(std::exception e)
    {
        handleClose();
    }
}

void CChatSession::handleClose()
{
    socket->disconnectFromHost();
    shunt(new CLogoutHandler(server,this->parent()));
}

void CChatSession::push(QByteArray bytes)
{
    socket->write(bytes);
    socket->flush();
}

void CChatSession::onReadyRead()
{
    collectIncomingData(socket->readAll());
    foundTerminator();
}
